package com.minshenglife.zanzan.web.weixin.service;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.minshenglife.zanzan.entity.EMOUserGroup;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.service.EMOUserService;

@Component
public class EMOWXUserService {
	Logger log = LoggerFactory.getLogger(EMOWXUserService.class);

	@Resource
	EMOUserService emoUserService;
	@Resource
	WXAccTokenService tokenService;

	/**
	 * 用户分组（微信组id，101：内勤组，102：外勤组）
	 * 
	 * @param content
	 * @throws Exception
	 */
	public Message grouping(String content, String openid) {
		log.info("start grouping -------------------------");
		log.info("user's openid is "+openid);
		Message message = null;
		try {
			// {"openid":"oDF3iYx0ro3_7jD4HFRDfrjdCM58","to_groupid":108}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("openid", openid);
//			jsonObject.put("openid", "oksggt4eG4wzz-EDNNHVa9_eaciY");
			boolean con = checkTrue(content);
			log.debug("user input content is "+con);
			if (!con) {
				message = new Message(Message.STATE_one, "请按照以下方式验证分组：#姓名:工号");
			} else {
				String[] arr = getInfo(content);
				if(arr.length != 2){
					message = new Message(Message.STATE_one, "请按照以下方式验证分组：#姓名:工号");
				}else{
					String group = judgeFieldOrOffice(arr);
					if (group != null && !group.equals("")) {
						if (group.equals("office")) {	//内勤
							jsonObject.put("to_groupid", 100);
						} else if (group.equals("field")) {	//外勤
							jsonObject.put("to_groupid", 101);
						}
						String token = tokenService.getEMOWXAccToken();
						log.debug("get token is " + token);
						log.debug("post group json " + jsonObject.toString());
						boolean result = EMOWXBaseServcie.removeUserGroup(jsonObject.toString(), token);
						if(result){
							EMOUserGroup emoUser = new EMOUserGroup();
							emoUser.setEmpId(arr[1]);
							emoUser.setEmpType(group);
							emoUser.setOpenid(openid);
							emoUser.setWxGroupId(jsonObject.getString("to_groupid"));
							emoUserService.add(emoUser);
							message = new Message(Message.STATE_200,"验证并分组成功");
						}else{
							message = new Message(Message.STATE_one,"验证成功但分组失败，请重新发送");
						}
					}else{
						message = new Message(Message.STATE_one,"您不是公司员工，请自觉离开！");
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.debug("移动用户 " + openid + " 分组失败");
			message = new Message(Message.STATE_one,"服务器异常");
		}
		log.info("end grouping -------------------------");
		return message;
	}

	private String[] getInfo(String str) {
		String[] arr=new String[2];
		try {
			arr[0]=str.substring(1,str.indexOf(":"));
			arr[1]=str.substring(str.indexOf(":")+1,str.length());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return arr;
	}

	/**
	 * 判断是内勤或外勤
	 * 
	 * @param args (args[0]:姓名，args[1]：工号)
	 * @return
	 */
	public String judgeFieldOrOffice(String[] args) {
		List users = null;
		String type = "";
		type = "office";
//		users = emoUserService.findFromOffice(args[0], args[1]);
//		if (users != null && users.size() > 0) {
//			type = "office";
//		} else {
//			users = emoUserService.findFromField(args[0], args[1]);
//			if (users != null && users.size() > 0) {
//				type = "field";
//			}
//		}
		return type;
	}

	private boolean checkTrue(String content) {
		if("".equals(content)){
			return false;
		}
		String str=content.substring(1);
		if(!"#".equals(content.substring(0,1))){
			return false;
		}else if(str.indexOf(":")==-1){
			return false;
		}else if("".equals(str.substring(0, str.indexOf(":")))){
			return false;
		}
		return true;
	}

	public static void main(String[] sdf) {
		String content = "#lisi:adfsadfdd";
		String content1 = "lisi:adfsadfdd;";
		String str = content.substring(1);
		System.out.println(str);
		System.out.println(str.indexOf(":"));
		System.out.println(str.substring(0, str.indexOf(":")));
		System.out.println(str.substring(str.indexOf(":") + 1, str.length()));
		String[] arr = str.split("\\:");
		System.out.println(arr.length);

		System.out.println((content.substring(1, content.length()))
				.split("\\:").length);

		System.out.println(Float.MAX_VALUE);
		System.out.println(Double.MAX_VALUE);
		
		String aa = "olcc4t5EZWzcr-5NNrbgY-x6easo";
		String bb = "olcc4t5EZWzcr-5NNrbgY-x6easo";
		if(aa.equals(bb)){
			System.out.println("wo feng lllllllllllllllllllllllllllllllllllllllllllll");
		}
	}
}
